package Future_FutureTask_13;
import java.util.concurrent.*;
public class 超时控制_带超时的任务执行 {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(3);
        final int TASK_COUNT = 6;
        Future<Integer>[] futures = new Future[TASK_COUNT];

        // 提交任务
        for (int i = 0; i < TASK_COUNT; i++) {
            final int taskId = i;
            futures[i] = executor.submit(new Callable<Integer>() {
                public Integer call() throws Exception {
                    int sleepTime = 800 + taskId * 200; // 任务耗时递增
                    Thread.sleep(sleepTime);
                    return sleepTime;
                }
            });
            System.out.println("已提交任务 " + taskId);
        }

        // 带超时获取结果
        for (int i = 0; i < TASK_COUNT; i++) {
            try {
                Integer result = futures[i].get(1000, TimeUnit.MILLISECONDS); // 1秒超时
                System.out.println("任务 " + i + " 成功完成，耗时: " + result + "ms");
            } catch (TimeoutException e) {
                System.out.println("任务 " + i + " 执行超时，尝试取消");
                futures[i].cancel(true);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        executor.shutdown();
    }
}